package top.yokey.shopai.zsdk;

import android.app.Activity;
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.OkHttpClient;
import top.yokey.shopai.zsdk.bean.BaseBean;
import top.yokey.shopai.zsdk.callback.BaseCallBack;
import top.yokey.shopai.zsdk.callback.DownCallBack;
import top.yokey.shopai.zsdk.callback.HtmlCallBack;

@SuppressWarnings("ALL")
public class ShopAISdk {

    private static volatile ShopAISdk instance = null;
    private String op = "";
    private String act = "";
    private String url = "";
    private String api = "";
    private String wap = "";
    private String key = "";
    private String param = "";
    private String apiUrl = "";
    private String pageNumber = "";
    private HttpParams httpParams = null;

    public static ShopAISdk get() {

        if (instance == null) {
            synchronized (ShopAISdk.class) {
                if (instance == null) {
                    instance = new ShopAISdk();
                }
            }
        }
        return instance;

    }

    public void init(Application application, String url, String api, String wap, String act, String op, String pageNumber, String key) {

        this.url = url;
        this.api = api;
        this.wap = wap;
        this.act = act;
        this.op = op;
        this.key = key;
        this.apiUrl = "";
        this.pageNumber = pageNumber;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.followRedirects(false).followSslRedirects(false);
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(application)));
        OkGo.getInstance().init(application).setOkHttpClient(builder.build());

    }

    public ShopAISdk ready(String act, String op) {

        param = url + api + "?" + this.act + "=" + act + "&" + this.op + "=" + op + "&key=" + key + "&";
        apiUrl = param;
        httpParams = new HttpParams();
        httpParams.put("key", key);
        return this;

    }

    public ShopAISdk add(String key, String value) {

        if (TextUtils.isEmpty(value)) {
            return this;
        }
        param += key + "=" + value + "&";
        httpParams.put(key, value);
        return this;

    }

    public ShopAISdk add(String key, File value) {

        if (value == null) {
            return this;
        }
        param += key + "=FILE&";
        httpParams.put(key, value);
        return this;

    }

    public ShopAISdk add(HashMap<String, String> hashMap) {

        String key, value;
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            key = entry.getKey().toString();
            value = hashMap.get(key);
            httpParams.put(key, value);
            param += key + "=" + value + "&";
        }

        return this;

    }

    public void get(BaseCallBack baseCallBack) {

        Log.i("yokey_tag", "HttpGetParams:" + param);
        OkGo.<String>get(apiUrl).tag(this).params(httpParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    String result = response.body();
                    Log.i("yokey_tag", "HttpGetResult:" + result);
                    BaseBean baseBean = new BaseBean();
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.has("code"))
                        baseBean.setCode(jsonObject.getInt("code"));
                    if (jsonObject.has("datas"))
                        baseBean.setDatas(jsonObject.getString("datas"));
                    if (jsonObject.has("hasmore"))
                        baseBean.setHasmore(jsonObject.getBoolean("hasmore"));
                    if (jsonObject.has("page_total"))
                        baseBean.setPageTotal(jsonObject.getInt("page_total"));
                    String data = baseBean.getDatas();
                    if (TextUtils.isEmpty(data) || data.equals("[]") || data.equals("{}")) {
                        if (baseCallBack != null) {
                            baseCallBack.onFailure("empty");
                        }
                        return;
                    }
                    if (data.length() <= 2) {
                        if (baseCallBack != null) {
                            baseCallBack.onSuccess(result, baseBean);
                        }
                        return;
                    }
                    jsonObject = new JSONObject(data);
                    if (jsonObject.has("error")) {
                        if (baseCallBack != null) {
                            baseCallBack.onFailure(jsonObject.getString("error"));
                        }
                        return;
                    }
                    if (baseCallBack != null) {
                        baseCallBack.onSuccess(result, baseBean);
                    }
                } catch (Exception e) {
                    if (baseCallBack != null) {
                        baseCallBack.onFailure(e.getMessage());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (baseCallBack != null) {
                    baseCallBack.onFailure(response.getException().getMessage());
                }
            }
        });

    }

    public void getHtml(HtmlCallBack htmlCallBack) {

        Log.i("yokey_tag", "HttpGetParams:" + param);
        OkGo.<String>get(apiUrl).tag(this).params(httpParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (htmlCallBack != null) {
                    htmlCallBack.onSuccess(response.body());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (htmlCallBack != null) {
                    htmlCallBack.onFailure(response.getException().getMessage());
                }
            }
        });

    }

    public void post(BaseCallBack baseCallBack) {

        Log.i("yokey_tag", "HttpPostParams:" + param);
        OkGo.<String>post(apiUrl).tag(this).params(httpParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    String result = response.body();
                    Log.i("yokey_tag", "HttpPostResult:" + result);
                    BaseBean baseBean = new BaseBean();
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.has("code"))
                        baseBean.setCode(jsonObject.getInt("code"));
                    if (jsonObject.has("datas"))
                        baseBean.setDatas(jsonObject.getString("datas"));
                    if (jsonObject.has("hasmore"))
                        baseBean.setHasmore(jsonObject.getBoolean("hasmore"));
                    if (jsonObject.has("page_total"))
                        baseBean.setPageTotal(jsonObject.getInt("page_total"));
                    String data = baseBean.getDatas();
                    if (TextUtils.isEmpty(data) || data.equals("[]") || data.equals("{}")) {
                        if (baseCallBack != null) {
                            baseCallBack.onFailure("empty");
                        }
                        return;
                    }
                    if (data.length() <= 2) {
                        if (baseCallBack != null) {
                            baseCallBack.onSuccess(result, baseBean);
                        }
                        return;
                    }
                    jsonObject = new JSONObject(data);
                    if (jsonObject.has("error")) {
                        if (baseCallBack != null) {
                            baseCallBack.onFailure(jsonObject.getString("error"));
                        }
                        return;
                    }
                    if (baseCallBack != null) {
                        baseCallBack.onSuccess(result, baseBean);
                    }
                } catch (Exception e) {
                    if (baseCallBack != null) {
                        baseCallBack.onFailure(e.getMessage());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (baseCallBack != null) {
                    baseCallBack.onFailure(response.getException().getMessage());
                }
            }
        });

    }

    public void postHtml(HtmlCallBack htmlCallBack) {

        Log.i("yokey_tag", "HttpPostParams:" + param);
        OkGo.<String>post(apiUrl).tag(this).params(httpParams).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (htmlCallBack != null) {
                    htmlCallBack.onSuccess(response.body());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (htmlCallBack != null) {
                    htmlCallBack.onFailure(response.getException().getMessage());
                }
            }
        });

    }

    public void down(String url, DownCallBack downCallBack) {

        Log.i("yokey_tag", "HttpDownParams:" + url);
        OkGo.<File>get(url).tag(this).execute(new FileCallback() {
            @Override
            public void onStart(Request<File, ? extends Request> request) {
                super.onStart(request);
                if (downCallBack != null) {
                    downCallBack.onStart();
                }
            }

            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                if (downCallBack != null) {
                    downCallBack.onProgress(progress.fraction);
                }
            }

            @Override
            public void onSuccess(Response<File> response) {
                if (downCallBack != null) {
                    downCallBack.onSuccess(response.body());
                }
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                if (downCallBack != null) {
                    downCallBack.onFailure(response.message());
                }
            }
        });

    }

    public void getLocation(String url, HtmlCallBack htmlCallBack) {

        Log.i("yokey_tag", "HttpGetLocation:" + url);
        OkGo.<String>get(url).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                htmlCallBack.onSuccess(response.headers().get("Location"));
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (htmlCallBack != null) {
                    htmlCallBack.onFailure(response.getException().getMessage());
                }
            }
        });

    }

    public void setKey(String key) {

        this.key = key;

    }

    public String getUrl() {

        return url;

    }

    public void setUrl(String url) {

        this.url = url;

    }

    public String getWap() {

        return wap;

    }

    public void setWap(String wap) {

        this.wap = wap;

    }

    public String getPageNumber() {

        return pageNumber;

    }

    public void setPageNumber(String pageNumber) {

        this.pageNumber = pageNumber;

    }

    //自定义方法

    public String getWapUrl() {

        return url + wap;

    }

    public String getChatUrl() {

        return url + wap + "html/member/chat_info.html";

    }

    public String getFeedbackUrl() {

        return url + wap + "html/member/member_feedback.html";

    }

    public void setSupportWebView(Activity activity) {

        //noinspection deprecation
        CookieSyncManager.createInstance(activity);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        //noinspection deprecation
        cookieManager.removeAllCookie();
        cookieManager.setCookie(url, "key=" + key);
        //noinspection deprecation
        CookieSyncManager.getInstance().sync();
        //noinspection deprecation
        CookieSyncManager.createInstance(activity);

    }

    public String getChatUrl(String tId, String goodsId) {

        return url + wap + "html/member/chat_info.html?t_id=" + tId + "&goods_id=" + goodsId;

    }

    public String getStoreInfoUrl(String storeId) {

        return url + wap + "html/store_intro.html?store_id=" + storeId;

    }

    public String getGoodsUrl(String goodsId) {

        return url + wap + "html/product_info.html?goods_id=" + goodsId;

    }

    public String getPreDepositOrderAlipayUrl(String paySn) {

        ready("member_payment_recharge", "pd_pay");
        return apiUrl + "&key=" + key + "&pay_sn=" + paySn + "&payment_code=alipay";

    }

    public String getOrderAlipayUrl(String paySn) {

        ready("member_payment", "pay_new");
        return apiUrl + "&password=&rcb_pay=0&pd_pay=0&key=" + key + "&pay_sn=" + paySn + "&payment_code=alipay";

    }

    public String getCaptchaUrl(String codeKey) {

        ready("vercode", "index");
        return apiUrl + "&c=0.13585012803819396&k=" + codeKey;

    }

    //卖家的方法

    public String getSellerChatUrl(String tId) {

        return url + wap + "html/seller/chat_info.html?t_id=" + tId;

    }

}
